/*
 * Copyright (c) 2018. czmc All Rights Reserved.
 * Author: czmc
 * Email: zxc6355533@163.com
 * Encoding: UTF-8
 */

package top.stime21.myneighbours.module.me

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.PercentFormatter
import com.github.mikephil.charting.utils.ColorTemplate
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.fragment_me.*
import top.stime21.framework.extension.toActivity
import top.stime21.framework.extension.toActivityWithSerializable
import top.stime21.myneighbours.R
import top.stime21.myneighbours.api.ApiManager
import top.stime21.myneighbours.base.BuzBaseFragment
import top.stime21.myneighbours.base.io_main
import top.stime21.myneighbours.data.entity.User
import top.stime21.myneighbours.data.entity.UserSkill
import top.stime21.myneighbours.module.myneed.MyNeedActivity
import top.stime21.myneighbours.module.settings.SettingsActivity
import top.stime21.myneighbours.utils.ACache
import top.stime21.myneighbours.utils.ImageLoader


/**
 * Author: czmc  Email: zxc6355533@163.com
 * Version:	1.0  Date:2018/3/1
 */

class MeFragment : BuzBaseFragment() {
    override fun getLayoutId(): Int {
        return R.layout.fragment_me
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
        initChart()
        iv_settings.setOnClickListener(l)
        iv_avatar.setOnClickListener(l)
        btn_my_publish.setOnClickListener(l)
        btn_my_accept.setOnClickListener(l)
        btn_all.setOnClickListener(l)
        tv_signature.setOnClickListener(l)
    }

    private val l: View.OnClickListener = object : View.OnClickListener {
        override fun onClick(p0: View?) {
            when (p0) {
                iv_settings -> context!!.toActivity<SettingsActivity>()
                iv_avatar -> context!!.toActivity<EditInfoActivity>()
                btn_my_publish -> context!!.toActivityWithSerializable<MyNeedActivity>(0)
                btn_my_accept -> context!!.toActivityWithSerializable<MyNeedActivity>(1)
                btn_all -> context!!.toActivityWithSerializable<MyNeedActivity>(2)
                tv_signature->context!!.toActivity<EditSignatureActivity>()
            }
        }
    }

    private var user: User? = null

    fun initData() {
        user = ACache.get(context).getAsObject("user") as User?
        if(user ==null )return
        if (user!!.avatar != null)
            ImageLoader().loadCircle(user!!.avatar, iv_avatar)
        else {
            iv_avatar.setImageResource(R.drawable.ic_male)
        }
        tv_nickname.setText(user!!.nickName)
        if(TextUtils.isEmpty(user!!.signature)){
            tv_signature.setText("点击编辑签名")
        }else {
            tv_signature.setText(user!!.signature)
        }
        loadSkill()
    }

    fun initChart() {
        piechart.setUsePercentValues(true)
        piechart.getDescription().setEnabled(false)
        piechart.setExtraOffsets(5f, 10f, 5f, 5f)

        piechart.setDragDecelerationFrictionCoef(0.95f)

        piechart.setDrawHoleEnabled(true)
        piechart.setHoleColor(Color.WHITE)

        piechart.setTransparentCircleColor(Color.WHITE)
        piechart.setTransparentCircleAlpha(110)

        piechart.setHoleRadius(58f)
        piechart.setTransparentCircleRadius(61f)

        piechart.setDrawCenterText(true)

        piechart.setRotationAngle(0f)
        // enable rotation of the chart by touch
        piechart.setRotationEnabled(true)
        piechart.setHighlightPerTapEnabled(true)

        // piechart.setUnit(" €");
        // piechart.setDrawUnitsInChart(true);

        // add a selection listener
//        piechart.setOnChartValueSelectedListener(this)
        val l = piechart.getLegend()
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP)
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT)
        l.setOrientation(Legend.LegendOrientation.VERTICAL)
        l.setDrawInside(false)
        l.setXEntrySpace(7f)
        l.setYEntrySpace(0f)
        l.setYOffset(0f)
        // entry label styling
        piechart.setEntryLabelColor(Color.WHITE)
        piechart.setEntryLabelTextSize(12f)
    }
    fun setData(data: List<UserSkill>?) {
        if(data==null) return
        val entries = ArrayList<PieEntry>()
        for(i in data!!){
            entries.add(PieEntry(i.level.toFloat() , i.skill.name))
        }
        var dataset = PieDataSet(entries, "以上为开辟的领域")
        val colors = ArrayList<Int>()
        for (c in ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c)
        for (c in ColorTemplate.JOYFUL_COLORS)
            colors.add(c)
        for (c in ColorTemplate.COLORFUL_COLORS)
            colors.add(c)
        for (c in ColorTemplate.LIBERTY_COLORS)
            colors.add(c)
        for (c in ColorTemplate.PASTEL_COLORS)
            colors.add(c)
        colors.add(ColorTemplate.getHoloBlue())
        dataset.setColors(colors)
        val data = PieData(dataset)
        data.setValueFormatter(PercentFormatter())
        data.setValueTextSize(11f)
        data.setValueTextColor(Color.WHITE)
        piechart.setData(data)
        // undo all highlights
        piechart.highlightValues(null)

        piechart.invalidate()
        piechart.animateY(1400, Easing.EasingOption.EaseInOutQuad)
    }

    fun loadSkill() {
        if (user != null)
            ApiManager.ins().dataApi.userskills(user!!.userId).io_main().subscribe({ r ->
                if (r.isSuccess) {
                    if(r.data!=null && r.data!!.size>0)
                        setData(r.data)
                } else {
                    showToast("获取失败")
                }
            }, { t ->
                Logger.i(t.toString())
                showToast("获取失败")
            })
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

}